package com.ikun.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ikun.entity.req.UserDTO;
import com.ikun.service.UserService;
import com.ikun.util.JwtUtil;
import com.ikun.util.Result;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @ClassName: LoginController
 * @Author: 吴思伟
 * @CreateTime: 2025-03-26 10:08
 */
@Controller
@RequestMapping("/user")
@Tag(name = "登录模块", description = "登录相关接口")
public class LoginController {
    @Autowired
    private UserService userService;

    private static Map<String, Object> getStringObjectMap(UserDTO byUsername, String token) {
        Map<String, Object> userData = new HashMap<>();
        userData.put("roleName", byUsername.getRoleName());
        switch (byUsername.getRoleName()) {
            case "超级管理员":
                userData.put("href", "index2.html");
                break;
            case "管家":
                userData.put("href", "index3.html");
                break;
            case "员工":
                userData.put("href", "index4.html");
                break;
            case "业主":
                userData.put("href", "index5.html");
                break;
            default:
                userData.put("href", "error.html");
        }
        userData.put("token", token);
        return userData;
    }

    @GetMapping("/login")
    @ResponseBody
    @Operation(summary = "登录", description = "登录接口")
    public Result login(String username, String password) {
        // 查询用户名是否存在
        UserDTO byUsername = userService.findUserByName(username);
        if (byUsername == null) {
            return Result.error("用户名不存在");
        }
        if (byUsername.getPassword().equals(password)) {
            // 登录成功
            Map<String, Object> user = new HashMap<>();
            user.put("id", byUsername.getUserId());
            user.put("username", byUsername.getName());
            String token = JwtUtil.genToken(user);
            Map<String, Object> userData = getStringObjectMap(byUsername, token);
            userData.put("userId", byUsername.getUserId());
            userData.put("phone", byUsername.getPhone());
            return Result.success("登陆成功! ", userData);
        }
        // 登录失败
        return Result.error("密码错误");
    }

    @PostMapping("/updateInfo")
    @ResponseBody
    @Operation(summary = "修改个人信息", description = "修改个人信息接口")
    public Result updateInfo(String id, String phone, String password) {
        return Result.success(userService.updateInfo(id, phone, password));
    }
}
